package com.authentications.oauth2.auc.handler.unrealized;

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.http.AccessTokenRequiredException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName IamAuthenticationEntryPoint
 * @Author xiezhuocai
 * @Description TODO
 * @Date 2021/12/20 18:25
 */
public class AuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        if (authException instanceof AccessTokenRequiredException) {
            System.out.println("2. udpate log to 401");
        } else {
            System.out.println("2. add log 401");
        }

        request.setAttribute("logUpdated", "yes");
        super.commence(request, response, authException);
    }

    @Override
    protected ResponseEntity<?> enhanceResponse(ResponseEntity<?> response, Exception exception) {
        ResponseEntity<?> responseEntity = super.enhanceResponse(response, exception);
        Map<String, Object> payload = new LinkedHashMap(4);
        payload.put("data", responseEntity.getBody());
        payload.put("code", responseEntity.getStatusCodeValue());
        payload.put("msg", exception.getMessage());
        responseEntity = new ResponseEntity(payload, responseEntity.getHeaders(), responseEntity.getStatusCode());
        return responseEntity;
    }
}
